package com.xayy.mgt.service.impl;

import cn.kawins.base.result.CheckResult;
import cn.kawins.mybatis.base.BaseServiceImpl;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.xayy.mgt.mapper.AnticipatoryFailureMapper;
import com.xayy.mgt.model.AnticipatoryFailure;
import com.xayy.mgt.model.vo.AnticipatoryFailurePageVo;
import com.xayy.mgt.service.AnticipatoryFailureService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AnticipatoryFailureServiceImpl extends BaseServiceImpl<AnticipatoryFailure> implements AnticipatoryFailureService {
    @Resource
    private AnticipatoryFailureMapper anticipatoryFailureMapper;

    @Override
    public PageInfo<AnticipatoryFailure> pageList(AnticipatoryFailurePageVo pageVo) {
        PageMethod.startPage(pageVo.getPage(), pageVo.getSize());
        List<AnticipatoryFailure> anticipatoryFailures = anticipatoryFailureMapper.pageList(pageVo);
        return new PageInfo<>(anticipatoryFailures);
    }

    @Override
    public CheckResult<Object> saveAnticipatoryFailure(AnticipatoryFailure anticipatoryFailure) {
        CheckResult<?> checkName = checkName(anticipatoryFailure);
        if (checkName.no()) {
            return CheckResult.fail(checkName.getCheckMsg());
        }
        anticipatoryFailureMapper.insert(anticipatoryFailure);
        return CheckResult.success("新增成功");
    }

    @Override
    public CheckResult<Object> editAnticipatoryFailure(AnticipatoryFailure anticipatoryFailure) {
        anticipatoryFailureMapper.updateByPrimaryKey(anticipatoryFailure);
        return CheckResult.success("编辑成功");
    }

    @Override
    public CheckResult<Object> deleteAnticipatoryFailure(Long faultId) {
        anticipatoryFailureMapper.deleteByPrimaryKey(faultId);
        return CheckResult.success("删除成功");
    }

    @Override
    public CheckResult<Object> selectOneAnticipatoryDetail(Long id) {
        return CheckResult.success(selectOne(AnticipatoryFailure.builder().id(id).build()));
    }

    public CheckResult<?> checkName(AnticipatoryFailure anticipatoryFailure) {
        Example example = new Example(AnticipatoryFailure.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("exceptionName",anticipatoryFailure.getExceptionName()).andEqualTo("satelliteId",anticipatoryFailure.getSatelliteId());
        int i = anticipatoryFailureMapper.selectCountByExample(example);
        if(i>0){
            return CheckResult.fail(anticipatoryFailure.getExceptionName()+"名称已存在");
        }
        return CheckResult.success();
    }
}
